package com.hong.demo.other.flink;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 扁平映射
 * 安装：brew install netcat
 * 启动：nc -lvnp 9000
 * 输入：hello
 */
public class FlatMapTest {

    public static void main(String[] args) throws Exception {
        // 准备环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置运行模式
        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);

        // 加载数据源
        DataStreamSource<String> elementsSource = env.socketTextStream("127.0.0.1", 9000);

        // 数据转换
        SingleOutputStreamOperator<String> flatMap = elementsSource.flatMap(new FlatMapFunction<String, String>() {

            @Override
            public void flatMap(String element, Collector<String> out) {
                String[] worlds = element.split(",");
                for (String word : worlds) {
                    out.collect(word);
                }
            }
        });

        SingleOutputStreamOperator<String> source = flatMap.map(new MapFunction<String, String>() {

            @Override
            public String map(String value) {
                // 转成大写
                return value.toUpperCase();
            }
        });

        // 数据输出
        source.print();

        // 执行程序
        env.execute("flink-hello-world");
    }
}